package com.kj.platformlogistics.home.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.kj.platformlogistics.R;
import com.kj.platformlogistics.base.BaseActivity;
import com.kj.platformlogistics.constants.UrlConstants;
import com.kj.platformlogistics.home.adapter.StockListAdapter;
import com.kj.platformlogistics.home.model.StockListModel;
import com.kj.platformlogistics.http.HttpRequest;
import com.kj.platformlogistics.http.HttpStringCallBack;
import com.kj.platformlogistics.util.JsonUtils;
import com.kj.platformlogistics.util.SoftKeyboardUtils;
import com.kj.platformlogistics.util.ToastUtil;
import com.kj.platformlogistics.widget.PersonSelectBottomDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class StockListActivity extends BaseActivity implements View.OnClickListener {
    private RecyclerView rcView;
    private SmartRefreshLayout refresh;
    private LinearLayout llNodata;
    private List<StockListModel.ResultDTO> data;
    private List<String>orderList=new ArrayList();
    private StockListAdapter adapter;
    private TextView _barTvRight;
    private LinearLayout llBottom;
    private ImageView ivSelectAll;
    private TextView tvAssignment;
    private EditText etPhone;

    private Boolean isShow=false;
    private Boolean isSelectAll=false;
    private String phone="";
    private String userid="";

    public static void actionStart(Context context) {
        Intent intent = new Intent(context, StockListActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_stock_list;
    }

    @Override
    protected void initView() {
        setTitleText("待派送");
        refresh=findViewById(R.id.refresh);
        rcView=findViewById(R.id.rcCommon);
        etPhone=findViewById(R.id.etPhone);
        llNodata=findViewById(R.id.llNodata);
        tvAssignment=findViewById(R.id.tvAssignment);
        _barTvRight=findViewById(R.id._barTvRight);
        llBottom=findViewById(R.id.llBottom);
        ivSelectAll=findViewById(R.id.ivSelectAll);
        _barTvRight.setText("批量分配");
        _barTvRight.setTextColor(getResources().getColor(R.color.red));
        etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                phone=s.toString().trim();
            }

            @Override
            public void afterTextChanged(Editable s) { }
        });
        etPhone.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                //是否是回车键
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    //隐藏键盘
                    SoftKeyboardUtils.hideSoftKeyboard(StockListActivity.this);
                    //搜索
                    getData();
                }
                return false;
            }
        });
        tvAssignment.setOnClickListener(this::onClick);
        _barTvRight.setOnClickListener(this);
        llBottom.setOnClickListener(this::onClick);
        ivSelectAll.setOnClickListener(this::onClick);
        data=new ArrayList<>();

        getData();
    }

    @Override
    protected void initData() {

    }

    //获取数据
    public void getData(){
        JSONObject jsonObject=new JSONObject();

            try {
                if (!phone.equals("")){
                    jsonObject.put("phone",phone);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        new HttpRequest(StockListActivity.this).doPost(UrlConstants.logistics_getOrderStockList, null,jsonObject ,new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), StockListModel.class);
                        if (obj instanceof StockListModel) {
                            StockListModel model=(StockListModel) obj;
                                data.clear();
                                if (model.getResult().size() > 0) {
                                    llNodata.setVisibility(View.GONE);
                                    rcView.setVisibility(View.VISIBLE);
                                    data=model.getResult();
                                    adapter=new StockListAdapter(data);
                                    rcView.setLayoutManager(new LinearLayoutManager(StockListActivity.this));
                                    rcView.setAdapter(adapter);

                                    adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                                        }
                                    });

                                    adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                                        @Override
                                        public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                                            switch (view.getId()){
                                                case R.id.ivSelected:
                                                    if (data.get(position).getSelected()){
                                                        data.get(position).setSelected(false);
                                                    }else {
                                                        data.get(position).setSelected(true);
                                                    }
                                                    adapter.notifyDataSetChanged();
                                                    break;
                                                    case R.id.tvAssignment:
                                                        //分配
                                                        orderList.add(data.get(position).getShopOrder());
                                                        PersonSelectBottomDialog dialog=new PersonSelectBottomDialog(StockListActivity.this);
                                                        dialog.setClicklistener(new PersonSelectBottomDialog.ClickListenerInterface() {
                                                            @Override
                                                            public void confirm(String userId) {
                                                                //确定  分配司机
                                                                userid=userId;
                                                                confirms(userId);
                                                                dialog.dismiss();
                                                            }
                                                        });
                                                        dialog.show(getSupportFragmentManager());
                                                    break;
                                            }
                                        }
                                    });
                                } else {
                                    rcView.setVisibility(View.GONE);
                                    refresh.finishRefreshWithNoMoreData();
                                    llNodata.setVisibility(View.VISIBLE);
                                }
                        }
                    }else {
                        Toast.makeText(StockListActivity.this,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                refresh.finishLoadMore();
                refresh.finishRefresh();
            }
        });
    }


    public void computeData(){
        orderList.clear();
        for (int i=0;i<data.size();i++){
            if (data.get(i).getSelected()){
                orderList.add(data.get(i).getShopOrder());
            }
        }
    }

    public void confirms(String userId){
        JSONObject jsonObject=new JSONObject();
        try {
            JSONArray jsonArray=new JSONArray(orderList);
            jsonObject.put("orderList",jsonArray);
            jsonObject.put("userId", userId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new HttpRequest(StockListActivity.this).doPost(UrlConstants.logistics_updOrderStockList, "", jsonObject,new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        ToastUtil toastUtil = new ToastUtil(getContext(), R.layout.popu_success1, "分配订单成功！", 1);
                        toastUtil.show();
                    }else {
                        ToastUtil toastUtil = new ToastUtil(getContext(), R.layout.popu_success1, message, 1);
                        toastUtil.show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) { }
        });
    }

    /**
     * 获取要使用的标题栏样式(此函数由子类重写)
     * @return
     */
    @Override
    protected int getTitleBarType() {
        return 0;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id._barTvRight:

                    if (!isShow){
                        if (data!=null&&data.size()>0){
                            for (int i=0;i<data.size();i++){
                                data.get(i).setShow(true);
                            }
                            adapter.notifyDataSetChanged();
                        }
                        llBottom.setVisibility(View.VISIBLE);
                        _barTvRight.setText("取消");
                    }else {
                        if (data!=null&&data.size()>0){
                            for (int i=0;i<data.size();i++){
                                data.get(i).setShow(false);
                            }
                            adapter.notifyDataSetChanged();
                        }
                        llBottom.setVisibility(View.GONE);
                        _barTvRight.setText("批量分配");
                    }
                isShow=!isShow;
                break;
            case R.id.ivSelectAll:
                //全选不全选
                if (!isSelectAll){
                    if (data!=null&&data.size()>0){
                        for (int i=0;i<data.size();i++){
                            data.get(i).setSelected(true);
                        }
                        adapter.notifyDataSetChanged();
                    }
                    ivSelectAll.setImageResource(R.mipmap.icon_selected_dot);

                }else {
                    //不全选
                    if (data!=null&&data.size()>0){
                        for (int i=0;i<data.size();i++){
                            data.get(i).setSelected(false);
                        }
                        adapter.notifyDataSetChanged();
                    }
                    ivSelectAll.setImageResource(R.mipmap.icon_unselected_dot);
                }
                isSelectAll=!isSelectAll;
                break;
            case R.id.tvAssignment:
                //分配
                computeData();
                if (orderList.size()<1){
                    Toast.makeText(StockListActivity.this,"请先选择要分配的订单",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (userid.equals("")){
                    Toast.makeText(StockListActivity.this,"请先选择要分配的司机",Toast.LENGTH_SHORT).show();
                    return;
                }
                confirms(userid);
                break;
        }
    }



}
